package org.dylan.common.dao.jdbc.support;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.util.Assert;

/**
 * 用于分页查询的ResultSetExtractor,会移动游标(cursor)至offset,并根据limit参数抽取数据
 * 
 * @author badqiu
 *
 */
public class OffsetLimitResultSetExtractor implements ResultSetExtractor<List<?>> {
	private int limit;
	private int offset;
	private RowMapper<?> rowMapper;
	
	public OffsetLimitResultSetExtractor(int offset,int limit,RowMapper<?> rowMapper) {
		Assert.notNull(rowMapper,"'rowMapper' must be not null");
		this.rowMapper = rowMapper;
		this.offset = offset;
		this.limit = limit;
	}

	public List<?> extractData(ResultSet rs) throws SQLException,DataAccessException {
		List<Object> results = new ArrayList<Object>(limit > 100 ? 100 : limit);
		int type = rs.getType();
		if (offset > 0) {
			if(type==ResultSet.TYPE_SCROLL_INSENSITIVE||type==ResultSet.TYPE_SCROLL_SENSITIVE){
				//支持数据集的滚动
				rs.absolute(offset+1);
			} else {
				limit = limit + offset;
			}
		}
		int rows = 0;
		while (rs.next()) {
			Object row = rowMapper.mapRow(rs, rows++);
			results.add(row);
			if(limit == (rows))
				break;
		}
		return results;
	}
	
}